package com.cee.auditlog.handler;

import com.cee.auditlog.process.AuditLogProcess;
import com.cee.util.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.core.task.TaskExecutor;

import java.util.ArrayList;
import java.util.List;

public class TransactionHandler {

    private Logger logger = LoggerFactory.getLogger(TransactionHandler.class);

    private List<SQLHandler> sqlHandlerList = new ArrayList<>();

    public void addSqlHandler(SQLHandler sqlHandler) {
        sqlHandlerList.add(sqlHandler);
    }

    public void clearAll() {
        logger.info("Clear the sqlHandlerList: {}", sqlHandlerList.size());
    }

    public void handleAll() {
        if (!sqlHandlerList.isEmpty()) {

            logger.info("Start to handle the sqlHandlerList: {}", sqlHandlerList.size());

            TaskExecutor taskExecutor = SpringContextUtil.getBean(TaskExecutor.class);
            try {
                AuditLogProcess auditLogProcess = SpringContextUtil.getBean(AuditLogProcess.class);

                taskExecutor.execute(new Runnable() {

                    @Override
                    public void run() {

                        for (SQLHandler sqlHandler : sqlHandlerList) {
                            sqlHandler.postHandle(auditLogProcess);
                        }

                        logger.info("Handle the sqlHandlerList end");
                    }
                });

                logger.info("Handle the sqlHandlerList end");
                TransactionHandlerContext.removeHandler();
            } catch (NoSuchBeanDefinitionException e) {
                logger.error("{}", e.getMessage());
            }

        } else {
            TransactionHandlerContext.removeHandler();
        }

    }


}
